getCSPGroupSummary <- function(groupcode, Pversion=0, details=FALSE, na.rm=FALSE) {
  groupinfo <- getDBGroup(groupcode)  # retrieve table with stock_id, code, from, to
  returnlist <- list()                # the function will return this list

  # getCSPGroupPattern ensures that CSP occurences is only calculated
  # within the from - to boundaries in groupmap

  patternlist <- getCSPGroupPattern(groupcode, Pversion=Pversion)

  nocandles <- list()  # nocandles contains the number of rows in every pattern
  columns <- list()    # columns contains the number of columns, should be the same for every pattern
  for (i in 1:length(patternlist)) {
    nocandles[[i]] <- dim(patternlist[[i]])[1]
    columns[[i]] <- dim(patternlist[[i]])[2]
    thissumobs <- colSums(patternlist[[i]], na.rm=na.rm)
    if (i==1) {
      # build numeric object 'sumobs' in first iteration of loop
      # normally, na.rm can be FALSE since CSP Pattern are cleanly calculated
      sumobs <- thissumobs
    } else {
      # in R, operations like this are great
      sumobs <- sumobs+ thissumobs
    }
    # add items to returnlist if details=TRUE
    if (details==TRUE) {
      thislist <- list()
      thislist[['sumobs']] <- nocandles[[i]]
      thislist[['firstdate']] <- index(first(patternlist[[i]]))
      thislist[['lastdate']] <- index(last(patternlist[[i]]))
      thismat <- matrix(
        c(thissumobs, thissumobs*100/nocandles[[i]]),
        nrow=length(thissumobs))
      rownames(thismat) <- names(sumobs)
      colnames(thismat) <- c("#Obs", "Pct")
      thislist[['matrix']] <- thismat
      returnlist[[names(patternlist)[i]]] <- thislist
    }
  }
  allcandles <- sum(unlist(nocandles))
  
  # form summary- matrix
  mat <- matrix(
    c(sumobs, sumobs*100/allcandles),
    nrow=length(sumobs))
  rownames(mat) <- names(sumobs)
  colnames(mat) <- c("#Obs", "Pct")
  summarylist <- list()
  summarylist[['sumobs']] <- allcandles
  summarylist[['matrix']] <- mat
  returnlist[['summary']] <- summarylist
  return(returnlist)
}
